<?php
namespace Admin\Controller;
class UserController extends CommonController {
	
	 /*
	 *  列表
	 *
	 */
	 public function index(){
		$act=I('get.act');
        if (!empty($act)&&$act==='search') {
		   $keywords=trim(urldecode(I('keywords')));	
           $condition=array();
           $con=array();
           if(!empty($keywords)){
			 $condition['realname']=array('like','%'.$keywords.'%');
		     $condition['mobile']=array('like','%'.$keywords.'%');
			 $condition['_logic']='OR';
           }
         $con['keywords']=$keywords;
        }
         
        if(count($condition)>0){
            
            
            $map['_complex']=$condition;
            
        }
        
        if($_SESSION['admin_info']['is_admin']=='1'){
            
        
            
        }else{
            
		   //$map['aid']=array('eq',$_SESSION['admin_info']['aid']); 
		   $map['branch_id']=array('eq',$_SESSION['admin_info']['dname']); 
		}
        
        
        
        
		$count=M('user')->where($map)->count();
		
        $p=getpage($count,9);
		 
		 foreach($con as $key=>$val) 
		 {
           $p->parameter[$key]   = urlencode($val);
         } 
		 
		 $user_arr=M('user')->where($map)->order('uid desc')->limit($p->firstRow.','.$p->listRows)->select();
	 
		 $this->user=$user_arr;
		 
		 $this->assign('page',$p->show());
	 
         $this->assign('con',$con);
		 
		 $this->display();
	 }
	 
	
	

   /*
	*
	*  添加+修改
	*
	*
	*/
	public function add(){
		$list = M('branch')->select();
		$this -> assign('list',$list);

	    $act=I('act','');
		
		$id=I('id',0,'intval');
		
	  	
		if($act=='add')
		{   
	        
			$realname=I('post.realname');
			$mobile=I('post.mobile');
			$upwd=I('post.upwd');
			$pic=I('post.pic','');
			$upoint = I('post.upoint');
			$branch_id = I('post.branch_id');
			if($_SESSION['admin_info']['is_admin'] == 0){
				$branch_id = $_SESSION['admin_info']['dname'];
			}
		
			!is_empty($realname,$mobile)?message(2,L('_IS_EMPTY_')):''; 
			
			
			if(!empty($id)){
			    
			    $old_icon_arr=M('user')->field('headimgurl')->where(array('uid'=>$id))->find();
			    
			    if($old_icon_arr['headimgurl']!==$pic)
			    {
			        
			        
			        !empty($old_icon_arr['headimgurl'])?unlink($old_icon_arr['headimgurl']):'';
			        
			        $pic=$this->base64_upload($pic,'user_');
			        
			    }else{
			        
			        $pic=$old_icon_arr['headimgurl'];
			    }
			    
			    
			    
			}else{
			    
			    
			    $pic=$this->base64_upload($pic,'slide_');
			    
			}
			
		 
            $db_arr=array(
			  'realname'=>$realname,
			  'mobile'=>$mobile,
			  'aid'=>$_SESSION['admin_info']['aid'],
              'create_time'=>time(),
              'headimgurl'=>$pic,
              'upoint' => $upoint,
              'branch_id' => $branch_id,
              'upwd'=>md5($upwd.C('SALT')),
			); 
			
			$is_exist=M('user')->where(array('mobile'=>$mobile,'uid'=>array('neq',$id)))->find();
		
			!empty($is_exist)?$this->error(L('_IS_EXIST_')):'';
		 	
			if(!empty($id)){
			    $db_arr=array(
			  						'realname'=>$realname,
			  						'mobile'=>$mobile,
			  						'aid'=>$_SESSION['admin_info']['aid'],
              						'create_time'=>time(),
              						'headimgurl'=>$pic,
              						//'upoint' => $upoint,
              						'branch_id' => $branch_id,
              						'upwd'=>md5($upwd.C('SALT')),
					); 
			    unset($db_arr['create_time']);
			    
			    if(empty($upwd)) unset($db_arr['upwd']);
			    	
				$lastId=M('user')->where(array('uid'=>$id))->save($db_arr);
				 
					
			}else{
			     
				 $lastId=M('user')->add($db_arr);
				 $m = new \Think\Model;
				 $num = $m -> query("select uid from y_user where mobile=\"$mobile\"");
				 $uid = $num[0]['uid'];
				 $add_aray = [
				 	'branch_id' => $branch_id,
				 	'type' => 'add',
				 	'add_id' => '初始积分',
				 	'aid'=>$_SESSION['admin_info']['aid'],
              		'update_time'=>time(),
				 	'upoint_add' => $upoint,
				 	'upoint_old' => 0,
				 	'note' => '初始积分',
				 	'upoint_new' => $upoint,
				 	'user_id' => $uid
				 ];
				 $lastId=M('upoint_log')->add($add_aray);
				 	 
			}
			
			if(!empty($lastId)){
			    
			    $this->success(L('_DO_SUCCEED_'),U('User/index'));
			    exit;
			    
			  }else{
			    
			    $this->error(L('_DO_FAILED_'));
			    
			 }
				// }
			
	  
		}

	    $edit=!empty($id)?M('user')->where(array('uid'=>$id))->find():'';
		
		$this->edit=$edit;
		
	  
		$this->display(); 
	}	
	
    /**
     * 
     * 
     * 积分操作
     * 
     * 
     */
	public function point(){
	    
	    $id=I('id');
	    
	    if(!empty($id)){
	        
	        $this->user=M('user')->where(array('uid'=>$id))->find();
	    }
	    
	    
	    
	    $this->display();
	}
	
	/*
	 *
	 *  获取项目名称
	 */
	public function get_project(){
	    
	    $opt=I('post.opt');
	    
	    if(!empty($opt)){
	        
	        $p_arr=M('project')->where(array('opt'=>$opt))->order('pid desc')->select();
	        
	        !empty($p_arr)?message(1,$p_arr):message(2,L('_DO_FAILED_'));
	    }
	    message(2,L('_DO_FAILED_'));
	}
	
	/**
	 * 
	 *获取积分 
	 * 
	 * 
	 */
	public function get_point(){
	    
	    $pid=I('post.pid');
	    
	    if(!empty($pid)){
	        
	        $p_arr=M('project')->field('point')->where(array('pid'=>$pid))->find();
	        
	        !empty($p_arr)?message(1,$p_arr['point']):message(2,L('_DO_FAILED_'));
	    }
	    message(2,L('_DO_FAILED_'));
	    
	    
	}
	
	/**
	 * 
	 * 处理积分
	 * 
	 */
	public function handle_point(){
	    
	    $act=I('post.act');
	    
	    if($act=='add'){
	        
	      $id=I('post.id');
	      $note = I('post.note'); 
	      $pid=I('post.pid');

	      
	      if(!empty($pid)){
	          
	          $p_arr=M('project')->where(array('pid'=>$pid))->find();
	          
	      }
	       
	      $db_arr=array(
	        'pid'=>$p_arr['pid'],  
	        'uid'=>$id,  
	        'aid'=>$_SESSION['admin_info']['aid'],  
	        'rtime'=>time(),
	        'rpoint'=>$p_arr['point'],
	         
	      );

	      $lastId=M('point_rec')->add($db_arr);
	     
	      if(!empty($lastId)){
	          $p_arr=M('project')->where(array('pid'=>$pid))->find();
	          if($p_arr['opt']=='-')
	          {

	          	$old_upoint = M('user')-> field('upoint') -> where(array('uid'=>$id))->find();
	          	  $data = array(
	          	  	'user_id' => $id,
	          	  	'add_id' => $p_arr['pname'],
	          	  	'type' => 'less',
	          	  	'note' => $note,
	          	  	'update_time' => time(),
	          	  	'change_id' => $_SESSION['admin_info']['aid'],
	          	  	'upoint_add' => $p_arr['point'],
	          	  	'upoint_old' => $old_upoint['upoint'],
	          	  	'upoint_new' => $old_upoint['upoint']-$p_arr['point']
	          	  		);
	          	  $sel = M('upoint_log') -> add($data);
	             
	              $eId1=M('user')->where(array('uid'=>$id))->setDec('upoint',$p_arr['point']);
	      
	              $eId2=M('user')->where(array('uid'=>$id))->setDec('rankpoint',$p_arr['point']);
	          }
	          elseif($p_arr['opt']=='+')
	          {

	          	  $old_upoint = M('user')-> field('upoint') -> where(array('uid'=>$id))->find();
	          	  $data = array(
	          	  	'user_id' => $id,
	          	  	'type' => 'add',
	          	  	'add_id' => $p_arr['pname'],
	          	  	'note' => $note,
	          	  	'update_time' => time(),
	          	  	'change_id' => $_SESSION['admin_info']['aid'],
	          	  	'upoint_add' => $p_arr['point'],
	          	  	'upoint_old' => $old_upoint['upoint'],
	          	  	'upoint_new' => $p_arr['point']+$old_upoint['upoint']
	          	  		);
	          	  $sel = M('upoint_log') -> add($data);
	              
	              $eId1= M('user')->where(array('uid'=>$id))->setInc('upoint',$p_arr['point']);
	              
	              $eId2= M('user')->where(array('uid'=>$id))->setInc('rankpoint',$p_arr['point']);
	              
	          }
	         
	                  
	          if(!empty($eId1)&&!empty($eId2))
	          {
	               
	              
	                  message(2,L('_DO_SUCCEED_'),U('User/index'));
	          }
	          else{
	              
	              M('point_rec')->where(array('rid'=>$lastId))->delete();
	          }
	              
	          message(2,L('_DO_FAILED_'));
	    
	          
	      }
	 
	        
	    }
	    
	    
	}
	
	
	  /*
	*
	* 删除
	*
	*/
	public function del(){
		
        $id=I('post.id',0);

        if(!empty($id)){
			
			$id_arr=is_array($id)?$id:array($id);
		   	// return $this->ajaxReturn($id_arr);
			foreach($id_arr as $k=>$v){
			    
			    M('goods_rec')->where('uid='.$v)->delete();
			    
			    // $icon_arr=M('user')->field('headimgurl')->where('uid='.$id)->find();
			    
			    // !empty($icon_arr['headimgurl'])?unlink($icon_arr['headimgurl']):'';
				  
				$delId=M('user')->where('uid ='.$v)->delete();
				
				if(empty($delId)) continue;
	  
			}
			
			message(1,L('_DO_SUCCEED_'),U('User/index'));
		}		
		message(2,L('_DO_FAILED_'));
	}
	 
	/*
	 *
	 * 积分清0
	 *
	 */
	public function point_clear(){
	    
	    $id=I('post.id',0);
	    
	    if(!empty($id))
	    {
	       
	       $cId=M('user')->where(array('uid'=>$id))->save(array('rankpoint'=>0,'upoint'=>0));
	       
	       !empty($cId)?message(1,L('_DO_SUCCEED_'),U('User/index')):message(2,L('_DO_FAILED_'));
	       
	    }
	 
	    message(2,L('_DO_FAILED_'));
	}
	
	
	/*-----------------------------公共函数---------------------------------------*/
	//上传图片
	public  function base64_upload($base64,$type='') {
	    
	    $base64_image = str_replace(' ', '+', $base64);//post的数据里面，加号会被替换为空格，需要重新替换回来，如果不是post的数据，则注释掉这一行
	    
	    if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $base64_image, $result)){
	        
	        //匹配成功
	        if($result[2] == 'jpeg'){
	            
	            $image_name = $type.date('YmdHis',time()).'.jpg'; //纯粹是看jpeg不爽才替换的
	            
	        }else{
	            $image_name = $type.date('YmdHis',time()).'.'.$result[2];
	        }
	        
	        $image_file = "./Uploads/{$image_name}";//服务器文件存储路径
	        
	        if (file_put_contents($image_file, base64_decode(str_replace($result[1], '', $base64_image)))){
	            
	            return $image_file;
	            
	        }else{
	            
	            return false;
	        }
	        
	    }
	    else
	    {
	        
	        return false;
	    }
	}
	
	/*************************************积分详情***************************************/ 
	public function full()
	{
		$user_id = I('id');
		$where['user_id'] = $user_id;
		$find = M('upoint_log') -> where($where) -> order('update_time desc') -> page($_GET['p'].',25') -> select();
		$this ->  assign('find',$find);
		$count = M('upoint_log') -> where($where) -> count();
		$Page =  new \Think\Page($count,25);
		$show = $Page -> show();
		$this -> assign('page',$show);
		$this -> display();
	}

	/*************************************部门积分操作**************************************/
	public function type()
	{
		$id=I('id');
	    
	    if(!empty($id)){
	        
	        $this->user=M('user')->where(array('uid'=>$id))->find();
	    }
		$type = M('branch')->select();
		$this -> assign('type',$type);
		$num = '';
		$this -> assign('num',$num);
		$this -> display();
	}
	//获取部门积分区间ajax
	public function jiden_qujian_ajax(){
		//部门
		$branch = trim(I('post.branch'));
		//项目
		$type = trim(I('post.type'));
		if(!$branch || !$type) return $this->ajaxReturn(['code'=>0,'data'=>'','msg'=>'参数错误']);
		$where['branch_id'] = $branch;
		$where['category_name'] = $type;
		$re = M('category')->where($where)->find();
		if(!$re) return $this->ajaxReturn(['code'=>0,'data'=>'','msg'=>'查询区间失败']);
			$data = array(
				'min'=>$re['min_jifen'],
				'max'=>$re['max_jifen']
			);
		return $this->ajaxReturn(['code'=>200,'data'=>$data,'msg'=>$re]);
	}


	public function number()
	{
		$bid = trim(I('get.bid'));
		$opt = trim(I('get.opt'));
		if ($opt == 'add') 
		{
			$opt = '+';
		}
		else if ($opt == 'less') 
		{
			$opt = '-';
		}
		if (!empty($bid)) 
		{
			$model = new \Think\Model();
			$type = $model -> query("select * from y_branch_and_creategory where opt=\"$opt\" and id=\"$bid\"");
			
			$this -> ajaxReturn($type);
		}
		$this -> ajaxReturn('');
	}

	public function add_pint()
	{
		  $id=I('get.id');
	      $note = I('get.note');
	      $add_number = I('get.add'); 
	      $branch_id = I('get.bid');
	      $opt=I('get.opt');
	      $ty = I('get.type');
	      if (!empty($opt) && !empty($id) && !empty($note) && !empty($add_number)) 
	      {
	      	$model = new \Think\Model();
			$type = $model -> query("select * from y_user where uid=\"$id\"");
			$old_upoint = $type[0]['upoint'];
			if ($opt == 'add') 
			{ 
				$upoint = $add_number + $old_upoint;
				 $data = array(
	          	  	'user_id' => $id,
	          	  	'type' => 'add',
	          	  	'add_id' => $ty,
	          	  	'note' => $note,
	          	  	'update_time' => time(),
	          	  	'change_id' => $_SESSION['admin_info']['aid'],
	          	  	'upoint_add' => $add_number,
	          	  	'upoint_old' => $old_upoint,
	          	  	'upoint_new' => $upoint,
	          	  	'branch_id' => $branch_id
	          	  		);
				 
	          	  $sel = M('upoint_log') -> add($data);
	          	  $model = new \Think\Model();
	          	  $model -> execute("update y_user set upoint = \"$upoint\" where uid=\"$id\"");
	          	  $this->ajaxReturn('isok');

			}
			else if ($opt == 'less') 
			{
				$upoint =  $old_upoint - $add_number;
				 $data = array(
	          	  	'user_id' => $id,
	          	  	'type' => 'less',
	          	  	'add_id' => $ty,
	          	  	'note' => $note,
	          	  	'update_time' => time(),
	          	  	'change_id' => $_SESSION['admin_info']['aid'],
	          	  	'upoint_add' => $add_number,
	          	  	'upoint_old' => $old_upoint,
	          	  	'upoint_new' => $upoint,
	          	  	'branch_id' => $branch_id
	          	  		);
	          	  $sel = M('upoint_log') -> add($data);
	          	  $model = new \Think\Model();
	          	  $model -> execute("update y_user set upoint = \"$upoint\" where uid=\"$id\"");
	          	  $this->ajaxReturn('isok');
			}
			
	      }
	      $this->ajaxReturn('isok');
	}

}

 